package com.example.demo.utils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.security.MessageDigest;

/**
 * 通用工具类
 */
public class CommonUtil {
    /**
     * 通过多个层级获取ip地址
     * @param request
     * @return
     */
    public static String getIpAdd(HttpServletRequest request){
        //ip地址变量
        String ip = null;
        try{
            //从请求头中获取ip地址
            ip = request.getHeader("x-forwarded-for");
            //如果ip为空或者长度为0或者为unknown
            if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
                ip = request.getHeader("Proxy-Client-IP");
            }
            if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
                ip = request.getRemoteAddr();
            }
            //判断ip地址是否为本机,如果是本机，根据网卡获取ip
            if("127.0.0.1".equals(ip)){
                InetAddress inet = null;
                inet = InetAddress.getLocalHost();
                ip = inet.getHostAddress();
            }
            //对于通过多个代理的情况，第一个ip为客户端真是ip,多个ip按照","分割
            if(ip != null && ip.length() > 15){
                int i = ip.indexOf(",");
                if(i > 0){
                    ip = ip.substring(0,i);
                }
            }
        }catch(Exception e){
            ip = "";
        }
        return ip;
    }

    /**
     * 将传入的数据进行MD5加密
     * @param data
     * @return
     */
    public static String MD5(String data){
        try{
            //加密协议
            MessageDigest md = MessageDigest.getInstance("MD5");
            //将字符串转为字节数组进行家吗
            byte[] array = md.digest(data.getBytes("UTF-8"));
            //字符串处理
            StringBuilder sb = new StringBuilder();
            //遍历加密后的字节数组
            for(byte item : array){
                //todo 这里要百度 & 0xFF
                sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1,3));
            }
            return sb.toString();
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
